package com.example.gobang.game;

import com.example.gobang.model.UserInfo;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 房间管理器
 */
@Component
public class RoomManager {
    // 关联key = 房间id 和 value = 房间
    ConcurrentHashMap<String, Room> roomIdToRoom = new ConcurrentHashMap<>();
    // 关联 key = 用户id 和 key =  房间id
    ConcurrentHashMap<Integer, String> userIdToRoomId = new ConcurrentHashMap<>();

    // 添加房间id 和 房间
    public void add(Room room, Integer userId1, Integer userId2) {
        // 添加房间id
        roomIdToRoom.put(room.getRoomId(), room);
        userIdToRoomId.put(userId1, room.getRoomId());
        userIdToRoomId.put(userId2, room.getRoomId());
    }

    //    删除房间
    public void remove(String roomId, Integer userId1 , Integer userId2) {
        roomIdToRoom.remove(roomId);
        userIdToRoomId.remove(userId1);
        userIdToRoomId.remove(userId2);
    }

    //    房间id获取房间
    public Room getByRoomId(String roomId) {
        return roomIdToRoom.get(roomId);
    }

    //    用户id 获取房间
    public Room getByUserId(Integer userId) {
        String roomId = userIdToRoomId.get(userId);
//        如果用户id 不存在就返回null
        if (roomId == null) {
            return null;
        }

//        最终得到的房间id 返回房间
        return roomIdToRoom.get(roomId);
    }

}
